package com.example.function;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.adapter.TeacherAdapterInAddCourse;
import com.example.database.DatabaseHelper;
import com.example.pojo.Teacher;
import com.example.student.R;

import java.util.ArrayList;
import java.util.List;

public class AddOptionalCourseActivity extends AppCompatActivity {
    private ListView listViewTeachers;
    private Spinner spinnerWeek, spinnerStartWeek, spinnerEndWeek, spinnerStartTime, spinnerEndTime;
    private DatabaseHelper dbHelper;
    private List<Teacher> teachers;
    private TeacherAdapterInAddCourse adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_add_optional_course);
        // 初始化数据库帮助类
        dbHelper = new DatabaseHelper(this);
        // 获取传递的数据
        Intent intent = getIntent();
        String courseId = intent.getStringExtra("course_id");
        String courseName = intent.getStringExtra("course_name");
        String collegeName = intent.getStringExtra("college");

        // 显示课程信息
        TextView textViewCourseId = findViewById(R.id.textViewCourseId);
        TextView textViewCourseName = findViewById(R.id.textViewCourseName);
        TextView textViewCollege = findViewById(R.id.textViewCollegeName);
        textViewCourseId.setText("课程ID：" + courseId);
        textViewCourseName.setText("课程名称：" + courseName);
        textViewCollege.setText("学院：" + collegeName);

        // 初始化UI组件
        listViewTeachers = findViewById(R.id.listViewTeachers);
        spinnerWeek = findViewById(R.id.spinnerWeek);
        spinnerStartWeek = findViewById(R.id.spinnerStartWeek);
        spinnerEndWeek = findViewById(R.id.spinnerEndWeek);
        spinnerStartTime = findViewById(R.id.spinnerStartTime);
        spinnerEndTime = findViewById(R.id.spinnerEndTime);

        // 查询并显示教师列表
        getTeachersNotTeachingCourse(courseId, collegeName);
        // 初始化适配器
        adapter = new TeacherAdapterInAddCourse(this, teachers);
        // 绑定 ListView
        listViewTeachers = findViewById(R.id.listViewTeachers);
        listViewTeachers.setAdapter(adapter);

        // 处理点击事件
        listViewTeachers.setOnItemClickListener((parent, view, position, id) -> {
            if (adapter.getSelectedPosition() == position) {
                adapter.setSelectedPosition(-1); // 取消选中
            } else {
                adapter.setSelectedPosition(position); // 更新选中位置
            }
        });

        // 初始化周几、周数、时间的选择器
        initSpinners();

        // 添加可选课程的逻辑
        Button btnAdd = findViewById(R.id.btnAdd);
        btnAdd.setOnClickListener(v -> {
            // 执行添加逻辑
            addCourseToOptional(courseId);
        });
    }
    private void initSpinners() {
        // 初始化周几
        ArrayAdapter<CharSequence> weekAdapter = ArrayAdapter.createFromResource(this,
                R.array.week_days, android.R.layout.simple_spinner_item);
        weekAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerWeek.setAdapter(weekAdapter);

        // 初始化周数
        ArrayAdapter<CharSequence> weekRangeAdapter = ArrayAdapter.createFromResource(this,
                R.array.week_range, android.R.layout.simple_spinner_item);
        weekRangeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerStartWeek.setAdapter(weekRangeAdapter);
        spinnerEndWeek.setAdapter(weekRangeAdapter);

        // 初始化开始时间
        ArrayAdapter<CharSequence> startTimeAdapter = ArrayAdapter.createFromResource(this,
                R.array.start_time_range, android.R.layout.simple_spinner_item);
        startTimeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerStartTime.setAdapter(startTimeAdapter);

        // 初始化结束时间
        ArrayAdapter<CharSequence> endTimeAdapter = ArrayAdapter.createFromResource(this,
                R.array.end_time_range, android.R.layout.simple_spinner_item);
        endTimeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerEndTime.setAdapter(endTimeAdapter);

        // 设置开始时间的监听器
        spinnerStartTime.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                updateEndTimeOptions(position); // 更新结束时间的选项
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        spinnerStartWeek.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                updateEndWeekOptions(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }

    private void addCourseToOptional(String courseId) {
        // 获取选中教师的 ID
        int selectedTeacherId = getSelectedTeacherId();
        if (selectedTeacherId == -1) {
            Toast.makeText(this, "请选择教师", Toast.LENGTH_SHORT).show();
            return;
        }

        // 获取教室输入
        String classroom = ((EditText) findViewById(R.id.editTextClassroom)).getText().toString();
        if (classroom.isEmpty()) {
            Toast.makeText(this, "请输入教室", Toast.LENGTH_SHORT).show();
            return;
        }

        // 获取周数范围
        String startWeek = spinnerStartWeek.getSelectedItem().toString();
        String endWeek = spinnerEndWeek.getSelectedItem().toString();
        if (Integer.parseInt(startWeek) > Integer.parseInt(endWeek)) {
            Toast.makeText(this, "开始周数必须早于结束周数", Toast.LENGTH_SHORT).show();
            return;
        }

        // 获取时间范围
        String startTime = spinnerStartTime.getSelectedItem().toString();
        String endTime = spinnerEndTime.getSelectedItem().toString();
        if (compareTimes(startTime, endTime) >= 0) {
            Toast.makeText(this, "开始时间必须早于结束时间", Toast.LENGTH_SHORT).show();
            return;
        }

        // 获取周几
        String week = spinnerWeek.getSelectedItem().toString();

        // 组合周数范围
        String numWeek = startWeek + "-" + endWeek + "周";

        // 插入到 teach 表
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("course_id", courseId); // courseId 是从 Intent 中获取的
        values.put("teacher_id", selectedTeacherId);
        values.put("classroom", classroom);
        values.put("week", week);
        values.put("num_week", numWeek);
        values.put("start_time", startTime);
        values.put("end_time", endTime);

        // 执行插入操作
        long result = db.insert("teach", null, values);
        if (result == -1) {
            Toast.makeText(this, "添加失败，请重试", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "添加成功", Toast.LENGTH_SHORT).show();
            finish(); // 关闭当前页面
        }
    }
    private int compareTimes(String time1, String time2) {
        // 将时间字符串转换为分钟数进行比较
        int time1Minutes = convertTimeToMinutes(time1);
        int time2Minutes = convertTimeToMinutes(time2);
        return time1Minutes - time2Minutes;
    }

    private int convertTimeToMinutes(String time) {
        String[] parts = time.split(":");
        int hours = Integer.parseInt(parts[0]);
        int minutes = Integer.parseInt(parts[1]);
        return hours * 60 + minutes;
    }
    private int getSelectedTeacherId() {
        int selectedPosition = adapter.getSelectedPosition();
        if (selectedPosition == -1) {
            return -1; // 未选中任何教师
        }
        return Integer.parseInt(teachers.get(selectedPosition).getTeacherId());
    }

    private void getTeachersNotTeachingCourse(String courseId, String collegeName) {
        teachers = new ArrayList<>();
        SQLiteDatabase db = dbHelper.getReadableDatabase();

        // 查询该学院但没有教这门课的教师
        String query = "SELECT t.teacher_id, t.name, t.college, t.office, t.phone, t.job, t.age " +
                "FROM teacher t " +
                "WHERE t.college = ? AND t.teacher_id NOT IN " +
                "(SELECT teacher_id FROM teach WHERE course_id = ?)";
        Cursor cursor = db.rawQuery(query, new String[]{collegeName, courseId});

        while (cursor.moveToNext()) {
            Teacher teacher = new Teacher();
            teacher.setTeacherId(cursor.getString(0));
            teacher.setTeacherName(cursor.getString(1));
            teacher.setCollege(cursor.getString(2));
            teacher.setOffice(cursor.getString(3));
            teacher.setPhone(cursor.getString(4));
            teacher.setJob(cursor.getString(5));
            teacher.setAge(cursor.getInt(6));
            teachers.add(teacher);
        }

        cursor.close();
    }

    private void updateEndTimeOptions(int startTimePosition) {
        // 获取开始时间的值
        String startTime = getResources().getStringArray(R.array.start_time_range)[startTimePosition];

        // 获取所有结束时间的值
        String[] endTimes = getResources().getStringArray(R.array.end_time_range);

        // 过滤出比开始时间晚的结束时间
        List<String> validEndTimes = new ArrayList<>();
        for (String endTime : endTimes) {
            if (compareTimes(startTime, endTime) < 0) {
                validEndTimes.add(endTime);
            }
        }

        // 更新结束时间的 Spinner
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, validEndTimes);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerEndTime.setAdapter(adapter);
    }
    private void updateEndWeekOptions(int startWeekPosition) {
        List<String> endWeeks = new ArrayList<>();
        String[] weeks = getResources().getStringArray(R.array.week_range);

        for (int i = startWeekPosition; i < weeks.length; i++) {
            endWeeks.add(weeks[i]);
        }

        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, endWeeks);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerEndWeek.setAdapter(adapter);
    }
}